package com.xiaoke.common;

import com.xiaoke.domain.HttpCode;
import com.xiaoke.domain.ResponseResult;
import com.xiaoke.enums.AppHttpCodeEnum;
import com.xiaoke.exception.QueryException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.converter.HttpMessageNotReadableException;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 查询异常处理
     * @return 错误信息
     */
    @ExceptionHandler(QueryException.class)
    public ResponseResult QueryException() {
        return ResponseResult.errorResult(AppHttpCodeEnum.QUERYEXCEPTION);
    }



    /**
     * DTO参数异常验证处理
     * @param e 异常类
     * @return 错误信息
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult methodArgumentNotValidException(BindException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> messages = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        return  ResponseResult.errorResult(HttpCode.BAD_REQUEST,messages.get(0));
    }
    /**
     * 服务器未知异常
     */
//    @ExceptionHandler(Exception.class)
//    public ResponseResult doException(Exception e) {
//        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
//    }
}
